import { ref, reactive, computed } from 'vue'
import { defineStore, storeToRefs } from 'pinia'
import type { UserInfoType } from '@/types/user'
import { getUserInfoAPI2 } from '@/api/user'
import { getAddressListAPI } from '@/api/adress'
import { useCartStore } from './cart'

export const useAuthStore = defineStore(
  'auth',
  () => {
    // 控制对话框显示隐藏
    const isAuthDialogShow = ref(false)

    // 用户信息
    const userInfo = ref<UserInfoType>({
      id: 0,
      username: '',
      password: '',
      address: '',
      phone: '',
      birthday: '',
      avatar: '',
      balance: 0,
      email: ''
    })

    // 登录表单
    const loginForm = reactive({
      username: '',
      password: ''
    })

    // 注册表单
    const registerForm = reactive({
      username: '',
      password: '',
      passwordConfirm: ''
    })

    const resetLoginForm = () => {
      loginForm.username = ''
      loginForm.password = ''
    }

    const resetRegisterForm = () => {
      registerForm.username = ''
      registerForm.password = ''
      registerForm.passwordConfirm = ''
    }

    const isLogin = computed(() => Boolean(userInfo.value.id))

    const { cartList } = storeToRefs(useCartStore())
    // 退出登录
    const logout = () => {
      localStorage.removeItem('token')
      userInfo.value = {
        id: 0,
        username: '',
        password: '',
        address: '',
        phone: '',
        birthday: '',
        avatar: '',
        balance: 0,
        email: ''
      }

      cartList.value = []
    }

    // 获取用户信息
    const getUserInfo = async () => {
      userInfo.value = await getUserInfoAPI2()
    }

    return {
      loginForm,
      getUserInfo,
      registerForm,
      isAuthDialogShow,
      resetRegisterForm,
      resetLoginForm,
      userInfo,
      isLogin,
      logout
    }
  },
  {
    persist: true
  }
)
